#encoding=utf-8
#接口调用方法，对方请求我的
import time,ujson
import urllib,traceback
from django.conf.urls import patterns, include, url
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect

import ProtocolHelper
from websys.view import otherdata,systemdata,reportdata,cbyx_otherdata,cbyx_userdata,cbyx_systemdata,userdata
from websys.models import (
LogLogin,LogOnline,UserInfo,LogLead,LogConsumer,LogRecharge,LogBuyItem,RankStage,Reply_Record,Loading,LoginNews,Usegift_Record,Gift_Code
)
from gm_site import settings
import datetime
#time.mktime(time.strptime(_times,'%Y-%m-%d %H:%M:%S'))

urlpatterns = patterns('',
                   #玩家登陆
                   url(r'^login', 'websys.api.mzwsw.user_login', name='user_login'),
                   #玩家在线
                   url(r'^online', 'websys.api.mzwsw.user_online', name='user_online'),
                   url(r'^new', 'websys.api.mzwsw.user_newlead', name='user_newlead'),#新手
                   url(r'^account', 'websys.api.mzwsw.user_register', name='user_register'),#注册
                   url(r'^recharge', 'websys.api.mzwsw.user_recharge', name='user_recharge'),#充值
                   url(r'^consumer', 'websys.api.mzwsw.user_consumer', name='user_consumer'),#消费
                   #url(r'^module', 'websys.api.mzwsw.user_module', name='user_module'),#模板
                   url(r'^buy', 'websys.api.mzwsw.user_buy', name='user_buy'),#购买
                   url(r'^rank', 'websys.api.mzwsw.user_rank', name='user_rank'),#购买
                   #获取玩家问题,保存到后台
                   url(r'get_reply','websys.api.mzwsw.user_reply', name='user_reply'),
                   #客户端获取回复历史
                   url(r'return_reply','websys.api.mzwsw.user_return_reply', name='user_return_reply'),
                   url(r'loading','websys.api.mzwsw.user_loading',name='user_loading'),
                    url(r'get_loginnew','websys.api.mzwsw.get_login_new',name='get_login_new'),
                    url(r'use_gift', 'websys.api.mzwsw.use_gift', name='use_gift'),
                    url(r'timing_task', 'websys.api.mzwsw.timing_task', name='timing_task'),

            )

INTERFACE_ID='oss'
#解密数据
def decode_request(request):
    #print request
    t_str=request.META['QUERY_STRING']
    print '====================',t_str,type(t_str)
    # a = urllib.quote(t_str)
    # print a,'-------------------------------------=-=-=-=-----'
    if settings.is_decode==1:
        try:
            t_obj=ProtocolHelper.Decode_OSS(t_str,INTERFACE_ID)
        except:
            t_obj=None
        print t_str,'--decode_request-',t_obj
    else:
        t_obj=ujson.loads(urllib.unquote(t_str))
    return t_obj

#登陆的
#{u'uid': u'f19c89fea2bc11e79f33e89a8fcd41d7', u'area': u'test1', u'pid': u'TEST', u'reason': u'U_FLOGIN', u'gid': u'mzwsw',
# u'data': u'[{"ip":"192.168.0.123","created":1506583179.4030508995}]', u'order': u'63c6ebdda41d11e79f33e89a8fcd41d7'}
def user_login(request):
    t_res={'code':-1,'data':{}}
    t_obj=decode_request(request)
    if t_obj and ('uid' in t_obj) and ('data' in t_obj):
        print
        t_data=ujson.loads(t_obj['data'])[0]
        ll=LogLogin()
        _times=int(t_data['created'])
        format_times= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_times))
        print t_data['created'],format_times
        ll.create_time=format_times
        ll.ip=t_data['ip']
        ll.uid=t_obj['uid']
        ll.server=t_obj['area']
        ll.platform=t_obj['pid']
        ll.save()
        t_res['code']=0
    response = HttpResponse(ujson.dumps(t_res))
    response['Access-Control-Allow-Origin']='*'
    return  response

#在线的
#{u'uid': u'f19c89fea2bc11e79f33e89a8fcd41d7', u'area': u'test1', u'pid': u'TEST', u'reason': u'B_FRAG', u'gid': u'mzwsw',
# u'data': u'[{"created":1506583179.595498085}]', u'order': u'63c6ebe1a41d11e79f33e89a8fcd41d7'}
def user_online(request):
    t_res={'code':-1,'data':{}}
    t_obj=decode_request(request)
    if t_obj:
        #t_data=t_obj['data'][0]
        t_data=ujson.loads(t_obj['data'])[0]
        #_times=int(t_data['created'])
        time_server = time.time()
        dts = datetime.datetime.fromtimestamp(time_server)
        three_s = datetime.timedelta(minutes=4)
        format_times= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time_server))
        cur_time=format_times#time.mktime(time.strptime(_times,'%Y-%m-%d %H:00:00'))
        before_time=dts - three_s
        t_uid=t_obj['uid']
        t_ser=t_obj['area']
        if UserInfo.objects.filter(uid=t_uid).exists():
            user_info=UserInfo.objects.get(uid=t_uid)
            user_info.recently_online=cur_time
            user_info.save()
        #是否存在
        if LogOnline.objects.filter(uid=t_uid,server=t_ser,create_time__gt=before_time,create_time__lte=cur_time).exists():
            pass
        else:
            ll=LogOnline()
            ll.create_time=cur_time
            ll.uid=t_uid
            ll.server=t_ser
            ll.platform=t_obj['pid']
            ll.save()
        t_res['code']=0
    response = HttpResponse(ujson.dumps(t_res))
    response['Access-Control-Allow-Origin'] = '*'
    return  response

#新手引导
#{u'uid': u'6964f8105fe511e7956f5254000d335c', u'area': u'test1', u'pid': None, u'reason': u'NEW', u'gid': u'mzwsw',
#  u'data': u'[{"val":"1_1","created":1506591895.3879449368}]', u'order': u'aef74118a43111e79f33e89a8fcd41d7'}
def user_newlead(request):
    t_res={'code':-1,'data':{}}
    t_obj=decode_request(request)
    if t_obj:
        #t_data=t_obj['data'][0]
        t_data=ujson.loads(t_obj['data'])[0]
        _times=int(t_data['created'])
        format_times= time.strftime('%Y-%m-%d',time.localtime(_times))
        t_stage=t_data['val']
        t_step=0
        if t_stage.find('_')>0:
            t_step=int(t_stage.replace('_',''))
        elif t_stage=="DONE":
            t_step=100
        # cur_time=format_times#time.mktime(time.strptime(_times,'%Y-%m-%d %H:00:00'))
        t_uid=t_obj['uid']
        t_ser=(t_obj['area'] or '')
        # #是否存在
        if LogLead.objects.filter(uid=t_uid,server=t_ser,create_date=format_times).exists():
            ll=LogLead.objects.get(uid=t_uid,server=t_ser,create_date=format_times)
        else:
            ll=LogLead()
            ll.create_date=format_times
            ll.uid=t_obj['uid']
            ll.server=t_ser
            ll.platform=t_obj['pid'] or ''

        ll.stage=t_stage
        ll.step=t_step
        ll.save()
        t_res['code']=0
    response = HttpResponse(ujson.dumps(t_res))
    response['Access-Control-Allow-Origin'] = '*'
    return  response

#注册
#{u'uid': u'6964f8105fe511e7956f5254000d335c', u'area': None, u'pid': u'TEST', u'reason': None, u'gid': u'mzwsw',
#  u'data': u'[{"username":"\\u4f60\\u7684\\u540d\\u5b57","account":"testandy","created":1506591977.1343989372}]', u'order': u'dfb0c50ea43111e79f33e89a8fcd41d7'}
def user_register(request):
    t_res={'code':-1,'data':{}}
    t_obj=decode_request(request)
    if t_obj:
        #t_data=t_obj['data'][0]
        t_data=ujson.loads(t_obj['data'])[0]
        _times=int(t_data['created'])
        format_times= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_times))
        t_uid=t_obj['uid']
        t_ser=t_obj['area']
        if not t_ser:
            t_ser=''
        #是否存在
        if UserInfo.objects.filter(uid=t_uid,server=t_ser).exists():
            pass
            #ll=UserInfo.objects.get(uid=t_uid,server=t_ser)
        else:
            ll=UserInfo()
            ll.create_time=format_times
            ll.uid=t_obj['uid']
            ll.server=t_ser
            ll.platform=t_obj['pid'] or ''
            ll.account=t_data['account']
            ll.username=t_data['username']
            ll.save()
        t_res['code']=0
    response = HttpResponse(ujson.dumps(t_res))
    response['Access-Control-Allow-Origin'] = '*'
    return  response

#充值
#{u'uid': u'6964f8105fe511e7956f5254000d335c', u'area': u'test2', u'pid': u'TEST', u'reason': u'PAY_SUCCESS', u'gid': u'mzwsw',
# u'data': u'[{"note":"{\\"orderid\\":\\"xxx\\",\\"pfid\\":\\"TEST\\",\\"uid\\":\\"6964f8105fe511e7956f5254000d335c\\",\\"order_id\\":\\"xxx\\",\\"money\\":50,
# \\"isPay\\":true,\\"item\\":\\"50098\\",\\"time\\":1506676243,\\"serverid\\":\\"test2\\"}","amt":50,"unit":"goldpoint","created":1506676243.5780830383}]', u'order': u'1267ab88a4f611e79f33e89a8fcd41d7'}
#node --->{u'orderid': u'xxx', u'pfid': u'TEST', u'uid': u'6964f8105fe511e7956f5254000d335c', u'order_id': u'xxx', u'money': 50, u'time': 1506676243,
# u'item': u'50098', u'isPay': True, u'serverid': u'test2'}
def user_recharge(request):
    t_res={'code':-1,'data':{}}
    t_obj=decode_request(request)
    if t_obj:
        #t_data=t_obj['data'][0]
        t_data=ujson.loads(t_obj['data'])[0]
        _times=int(t_data['created'])
        format_times= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_times))

        t_node=ujson.loads(t_data['note'])
        ll=LogRecharge()
        ll.create_time=format_times
        ll.uid=t_node['uid']
        ll.server=t_node['serverid']
        ll.platform=t_node['pfid']
        ll.orderid=t_node['orderid']
        ll.order_id=t_node['order_id']
        ll.money=t_node['money']
        ll.isPay=t_node['isPay']
        ll.item=t_node['item']
        ll.account=UserInfo.objects.get(uid=t_node['uid']).account
        ll.save()
        t_res['code']=0
    response = HttpResponse(ujson.dumps(t_res))
    response['Access-Control-Allow-Origin'] = '*'
    return  response

#消费
#{u'uid': u'f19c89fea2bc11e79f33e89a8fcd41d7', u'area': u'test1', u'pid': u'TEST', u'reason': u'BA_FNBATTLE', u'gid': u'mzwsw',
# u'data': u'[{"amt":52,"unit":"gamepoint","created":1506583190.7919559479},{"amt":26,"unit":"gamepoint","created":1506583190.7954668999}]', u'order': u'6a9c55c7a41d11e79f33e89a8fcd41d7'}
def user_consumer(request):
    t_res={'code':-1,'data':{}}
    t_obj=decode_request(request)
    if t_obj:
        #t_data=t_obj['data'][0]
        arr_data=ujson.loads(t_obj['data'])
        for t_data in arr_data:
            _times=int(t_data['created'])
            format_times= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_times))

            ll=LogConsumer()
            ll.create_time=format_times
            ll.uid=t_obj['uid']
            ll.server=t_obj['area'] or ''
            ll.platform=t_obj['pid'] or ''
            ll.amt=t_data['amt']
            ll.unit=t_data['unit']
            ll.save()
        t_res['code']=0
    response = HttpResponse(ujson.dumps(t_res))
    response['Access-Control-Allow-Origin'] = '*'
    return  response

# #模块
# #{u'uid': u'6964f8105fe511e7956f5254000d335c', u'area': None, u'pid': u'TEST', u'reason': None, u'gid': u'mzwsw',
# #  u'data': u'[{"username":"\\u4f60\\u7684\\u540d\\u5b57","account":"testandy","created":1506591977.1343989372}]', u'order': u'dfb0c50ea43111e79f33e89a8fcd41d7'}
# def user_module(request):
#     t_res={'code':-1,'data':{}}
#     t_obj=decode_request(request)
#     if t_obj:
#         #t_data=t_obj['data'][0]
#         t_data=ujson.loads(t_obj['data'])[0]
#         # _times=int(t_data['created'])
#         # format_times= time.strftime('%Y-%m-%d %H:00:00',time.localtime(_times))
#         # cur_time=format_times#time.mktime(time.strptime(_times,'%Y-%m-%d %H:00:00'))
#         # #是否存在
#         # if LogOnline.objects.filter(create_time=cur_time).exists():
#         #     pass
#         # else:
#         #     ll=LogOnline()
#         #     ll.create_time=cur_time
#         #     ll.uid=t_obj['uid']
#         #     ll.server=t_obj['area']
#         #     ll.platform=t_obj['pid']
#         #     ll.save()
#         t_res['code']=0
#     response = HttpResponse(ujson.dumps(t_res))
#     response['Access-Control-Allow-Origin'] = '*'
#     return  response

#购买
#{u'uid': u'6964f8105fe511e7956f5254000d335c', u'area': u'test2', u'pid': None, u'reason': u'SHOP_BUY', u'gid': u'mzwsw',
# u'data': u'[{"num":1,"amt":95,"buy_id":"1","created":1506681799.6587359905}]', u'order': u'02164bf6a50311e79f33e89a8fcd41d7'}
def user_buy(request):
    t_res={'code':-1,'data':{}}
    t_obj=decode_request(request)
    if t_obj:
        #t_data=t_obj['data'][0]
        t_data=ujson.loads(t_obj['data'])[0]
        _times=int(t_data['created'])
        format_times= time.strftime('%Y-%m-%d %H:00:00',time.localtime(_times))

        ll=LogBuyItem()
        ll.create_time=format_times
        ll.uid=t_obj['uid']
        ll.server=t_obj['area']
        ll.platform=t_obj['pid'] or ''

        ll.amt=t_data['amt']
        ll.buy_id=t_data['buy_id']
        ll.num=t_data['num']
        ll.reason=t_obj['reason']
        ll.save()
        t_res['code']=0
    response = HttpResponse(ujson.dumps(t_res))
    response['Access-Control-Allow-Origin'] = '*'
    return  response

#排行榜
#{u'uid': None, u'area': u'test2', u'pid': u'TEST', u'reason': u'FightRanking', u'gid': u'mzwsw',
# u'data': u'[{"ts":"1506767366","rank":[{"score":17,"uid":"c959a446a39711e7b13e5254000d335c","rank":1,"name":"\\u5cb3\\u68a6\\u5c9a"},
# {"score":267,"uid":"7d1d9398a39d11e7b13e5254000d335c","rank":2,"name":"\\u4e01\\u6653\\u7075"},
# {"score":310,"uid":"1d8fc072a39d11e7b13e5254000d335c","rank":3,"name":"\\u5355\\u9999\\u5bd2"},
# {"score":345,"uid":"c13bbc22a39c11e7b13e5254000d335c","rank":4,"name":"\\u82ae\\u5343\\u51dd"},
# {"score":561,"uid":"73ead9c4a39411e7950a5254000d335c","rank":5,"name":"\\u7687\\u96c5\\u5bb9"},
# {"score":2440,"uid":"ae124c48a39b11e7b13e5254000d335c","rank":6,"name":"\\u6c34\\u6653\\u7eff"},
# {"score":20701,"uid":"69d5bf58a3f811e7b13e5254000d335c","rank":7,"name":"\\u7a46\\u8fce\\u6d77"}],"created":1506767366.4124510288}]', u'order': u'3bd8c1c6a5ca11e7b7b05254000d335c'}
def user_rank(request):
    print '------------0-0-0-0-0-0-0-0-0-00-0rank---------------------------------------0-0---------'
    t_res={'code':-1,'data':{}}
    t_obj=decode_request(request)
    print t_obj,'--------------request--------------'
    if t_obj:
        #t_data=t_obj['data'][0]
        t_data=ujson.loads(t_obj['data'])[0]
        _times=int(t_data['ts'])
        format_times= time.strftime('%Y-%m-%d %H:00:00',time.localtime(_times))
        arr_rank=t_data['rank']
        for ii_item in arr_rank:
            ll=RankStage()
            ll.create_time=format_times
            ll.uid=ii_item['uid']
            ll.server=t_obj['area']
            ll.platform=t_obj['pid']

            ll.name=ii_item['name']
            ll.score=ii_item['score']
            ll.rankid=ii_item['rank']
            ll.stageid=_times
            ll.reason=t_obj['reason']
            ll.save()
        t_res['code']=0
    response = HttpResponse(ujson.dumps(t_res))
    response['Access-Control-Allow-Origin'] = '*'
    return  response

#======================================城堡其他接口===========================
#获取玩家问题,保存到后台
#api/mzwsw/get_reply?
#{'uid':15857585,'nickname':'昵称','content':'测试'','serverid':1,'title':'测试a'}
def user_reply(request):
    r_data={'code':-1,'data':{},'msg':''}
    t_obj = decode_request(request)
    print t_obj,'=============',type(t_obj)
    if t_obj:
        reply_info = Reply_Record()
        reply_info.uid=str(t_obj['uid'])
        reply_info.content=t_obj['content']
        reply_info.nickname=t_obj['nickname']
        reply_info.serverid=t_obj['serverid']
        reply_info.title=t_obj['title']
        reply_info.is_who=0
        reply_info.save()
        r_data['code']=0
        r_data['msg']='success'
    response = HttpResponse(ujson.dumps(r_data))
    response['Access-Control-Allow-Origin'] = '*'
    return response



#客户端获取回复历史
#api/mzwsw/return_reply?
#{'uid':14545955}
def user_return_reply(request):
    r_data = {'code': -1, 'data': [], 'msg': ''}
    t_obj = eval(decode_request(request))
    reply_info = Reply_Record.objects.filter(uid=str(t_obj['uid'])).order_by('-create_time')
    lists=[]
    for i in reply_info:
        reply_dic={}
        reply_dic['nickname']=i.nickname
        reply_dic['content']=i.content
        reply_dic['is_who']=i.is_who
        reply_dic['create_time']=i.create_time
        lists.append(reply_dic)
    r_data['data']=lists
    r_data['code']=0
    r_data['msg']='success'
    response = HttpResponse(ujson.dumps(r_data))
    response['Access-Control-Allow-Origin'] = '*'
    return response


#加载流失
#{'val':22}
def user_loading(request):
    r_data = {'code': -1, 'data': [], 'msg': ''}
    t_obj = decode_request(request)
    step=eval(t_obj['data'])[0]['val']
    date_times=datetime.datetime.now().strftime('%Y-%m-%d')

    if Loading.objects.filter(steps=step,date_time=date_times).exists():
        loading_info=Loading.objects.get(steps=step,date_time=date_times)
        loading_info.number += 1
        loading_info.save()
    else:
        loading_infos=Loading()
        loading_infos.steps=step
        loading_infos.number=1
        loading_infos.save()

    r_data['code'] = 0
    r_data['msg'] = 'success'
    response = HttpResponse(ujson.dumps(r_data))
    response['Access-Control-Allow-Origin'] = '*'
    return response


#====================萌战===================
#客户端获取登录公告

def get_login_new(request):
    r_data = {'code': -1, 'data':{}, 'msg': ''}

    login_info=LoginNews.objects.all()[0]

    new_dic={}
    if login_info:
        new_dic['content']=login_info.content
    else:
        new_dic['content'] ='无'
    r_data['data']=new_dic
    r_data['code'] = 0
    r_data['msg'] = 'success'
    response = HttpResponse(ujson.dumps(r_data))
    return response


#玩家使用礼物码
def use_gift(request):
    r_data = {'code': -1, 'data':{}, 'msg': ''}

    uid = request.GET['uid']
    sid = request.GET['sid']
    cdk = request.GET['cdk']
    print uid,sid,cdk,'========================sssss========'
    cdk_list=Gift_Code.objects.filter(code=cdk)
    if not cdk_list:
        r_data['code']=2
        r_data['msg']='cdk is not exist!'
        return HttpResponse(ujson.dumps(r_data))

    types=cdk_list[0].gift_type
    print types,'--------------------2------------'
    if int(types)==1:
        if not Usegift_Record.objects.filter(uid=uid,server_id=sid,cdk=cdk).exists():
            dic_info={}
            items=cdk_list[0].items
            if '|' in str(items):
                many_list=str(items).split('|')
                for each in many_list:
                    d_list=str(each).split('*')
                    dic_info[str(d_list[0])]=int(d_list[1])
            else:
                d_list = str(items).split('*')
                dic_info[str(d_list[0])] = int(d_list[1])
            use_info=Usegift_Record()
            use_info.uid=uid
            use_info.server_id=sid
            use_info.cdk=cdk
            use_info.piciid = cdk_list[0].serial_no
            use_info.save()
            r_data['data']['items']=dic_info
            r_data['code']=0
            r_data['msg']='success'
            return HttpResponse(ujson.dumps(r_data))

        else:
            r_data['code'] = 1
            r_data['msg'] = 'user aready use this cdk!'
            return HttpResponse(ujson.dumps(r_data))
    else:
        print '---------------0-----------------'
        cdk_info=Gift_Code.objects.get(code=cdk)
        if int(cdk_info.activity_id)==0:
            if not Usegift_Record.objects.filter(uid=uid,piciid=cdk_info.serial_no,server_id=sid).exists():
                dic_info = {}
                items = cdk_list[0].items
                if '|' in str(items):
                    many_list = str(items).split('|')
                    for each in many_list:
                        d_list = str(each).split('*')
                        dic_info[str(d_list[0])] = int(d_list[1])
                else:
                    d_list = str(items).split('*')
                    dic_info[str(d_list[0])] = int(d_list[1])

                cdk_info.activity_id=1
                cdk_info.save()
                use_info = Usegift_Record()
                use_info.uid = uid
                use_info.server_id = sid
                use_info.cdk = cdk
                use_info.piciid=cdk_info.serial_no
                use_info.save()
                r_data['data']['items'] = dic_info
                r_data['code'] = 0
                r_data['msg'] = 'success'
                return HttpResponse(ujson.dumps(r_data))
            else:
                r_data['code'] = 1
                r_data['msg'] = 'this uid have used!'
                return HttpResponse(ujson.dumps(r_data))
        else:
            r_data['code'] = 1
            r_data['msg'] = 'cdk is not used'
            return HttpResponse(ujson.dumps(r_data))


#定时刷新服务器，渠道
def timing_task(request):
    r_data = {'code': -1, 'msg': ''}
    try:
        otherdata.getPlatformInfo_list()
        reportdata.getqudao_list()
        reportdata.getPlatformInfo_list()
        systemdata.getPlatformInfo_list()
        systemdata.getPlatformInfo_list2()
        userdata.getPlatformInfo_list()
        cbyx_systemdata.getPlatformInfo_list()
        cbyx_systemdata.getPlatformInfo_list2()
        cbyx_userdata.getPlatformInfo_list()
        cbyx_otherdata.getPlatformInfo_list()
        r_data['code']=0
        r_data['msg']='success'
        return HttpResponse(ujson.dumps(r_data))
    except:
        r_data['code']=0
        r_data['msg']='fail'
        return HttpResponse(ujson.dumps(r_data))


